<?php

namespace app\controller;

use app\exception\RequestException;
use app\model\Discount;
use app\model\User as UserModel;
use thans\jwt\facade\JWTAuth;
use think\Db;
use think\Request;

class User extends BaseController
{
    public function lists(): \think\Paginator
    {
        return UserModel::field('id, username, created_time')
            ->withCount('discount', false)
            ->order('id', 'desc')
            ->paginate();
    }

    public function checkNameExists($name, $id = 0): bool
    {
        $model = UserModel::field('id')
        ->where('username', $name)
         ->when($id, function($query) use ($id) {
            $query->where('id', '<>', $id);
        })
        ->find();

        return (bool)$model;
    }

    public function save(Request $request)
    {
        $param = $request->post();
        $rule  = [
            'username' => 'require'
        ];
        if (empty($param['id'])) {
            $rule['password'] = 'require';
        }
        $this->validate($param, $rule);

        if ($this->checkNameExists($param['username'], $param['id'] ?? 0)) {
            throw new RequestException('用户名称重复！');
        }
        if (!empty($param['id'])) {
            $model = UserModel::where('id', $param['id'])->find();
            if (!$model) {
                throw new RequestException('非法访问！');
            }
        } else {
            $model = new UserModel;
        }
        $model->username = $param['username'];
        if (!empty($param['password'])) {
            $model->password = $param['password'];
        }
        $model->save();
    }

    public function del($id)
    {
        $model = UserModel::where('id', $id)->find();
        if (!$model) {
            throw new RequestException('非法访问！');
        }
        $model->delete();
    }

    public function login($account, $password): string
    {
        $user = UserModel::where('account', $account)->find();
        if (!$user || $user->password !== $password) {
            throw new RequestException('账号或密码错误！');
        }

        return JWTAuth::builder($user->toArray());
    }

    public function info()
    {
        $user = clone $this->user;
        unset($user['password']);

        return $user;
    }

    public function discount(): \think\Paginator
    {
        return Discount::where('user_id', $this->user['id'])
            ->field('id, discount, line_id')
            ->with(
                [
                    'line' => function ($query) {
                        $query->field('id, name, price');
                    }
                ]
            )
            ->order('id', 'desc')
            ->paginate();
    }
}
